package com.sms.fileupload;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class DownServlet extends HttpServlet {
	public DownServlet() {
		super();
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.reset();
		
		response.setContentType("application/x-download");
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		
		String fileName = new String(request.getParameter("fileName").getBytes("ISO-8859-1"), "utf-8");//实际文件名，转码
		String saveName = new String(request.getParameter("saveName").getBytes("ISO-8859-1"), "utf-8");//保存在服务器上的文件名，转码
		String servletPath = this.getServletContext().getRealPath("/");
		String uploadFile = "uploadFile";
		String savePath = "" + servletPath + uploadFile + "\\" + saveName;
		
		File file = new File(savePath);
		InputStream is = new FileInputStream(file);
		OutputStream os = response.getOutputStream();

		//添加头信息
		fileName = URLEncoder.encode(fileName,"UTF-8");
		response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
		response.addHeader("Content-Length", (new Long(file.length())).toString());
		
		int i = -1;
		byte b[] = new byte[1024];
		i = is.read(b);
		while(i != -1) {
			os.write(b, 0, i);
			i = is.read(b);
		}
		
		is.close();
		os.flush();
		os.close();
		
		
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
	
	

}
